# -*- coding: utf-8 -*-
# @Time    : 2024/7/19 16:47
# @Author  : yujiahao
# @File    : 49_fastapi_test_main.py
# @description:扩展后的测试文件


"""
每当你需要客户端在请求中传递信息，但你不知道如何传递时，你可以通过搜索（谷歌）如何用 httpx 做，或者是用 requests 做，毕竟 HTTPX 的设计是基于 Requests 的设计的。

接着只需在测试中同样操作。

示例：

1. 传一个路径或查询参数，添加到 URL 上：
    response = client.get("/items/?name=foo")

2. 传一个 JSON 体，传一个 Python 对象（例如一个 dict）到参数 json：
    response = client.post("/items/", json={"name": "foo", "description": "bar"})

3. 如果你需要发送 Form Data 而不是 JSON，使用 data 参数：
    response = client.post("/login/", data={"username": "foo", "password": "bar"})

4. 要发送 headers，传 dict 给 headers 参数：
    response = client.get("/items/", headers={"Authorization": "Bearer mytoken"})

5. 对于 cookies，传 dict 给 cookies 参数：
    response = client.get("/items/", cookies={"session_id": "123456"})

关于如何传数据给后端的更多信息（使用 httpx 或 TestClient），可以查阅 HTTPX 文档（https://www.python-httpx.org/）。

信息：

注意 TestClient 接收可以被转化为 JSON 的数据，而不是 Pydantic 模型。

如果你在测试中有一个 Pydantic 模型，并且你想在测试时发送它的数据给应用，你可以使用在 JSON Compatible Encoder 介绍的 jsonable_encoder。


"""

import importlib
from fastapi.testclient import TestClient

app_main = importlib.import_module("49_fastapi_main")
app = app_main.app

client = TestClient(app)


def test_read_item():
    response = client.get("/items/foo", headers={"X-Token": "coneofsilence"})
    assert response.status_code == 200
    assert response.json() == {
        "id": "foo",
        "title": "Foo",
        "description": "There goes my hero",
    }


def test_read_item_bad_token():
    response = client.get("/items/foo", headers={"X-Token": "hailhydra"})
    assert response.status_code == 400
    assert response.json() == {"detail": "Invalid X-Token header"}


def test_read_nonexistent_item():
    response = client.get("/items/baz", headers={"X-Token": "coneofsilence"})
    assert response.status_code == 404
    assert response.json() == {"detail": "Item not found"}


def test_create_item():
    response = client.post(
        "/items/",
        headers={"X-Token": "coneofsilence"},
        json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"},
    )
    assert response.status_code == 200
    assert response.json() == {
        "id": "foobar",
        "title": "Foo Bar",
        "description": "The Foo Barters",
    }


def test_create_item_bad_token():
    response = client.post(
        "/items/",
        headers={"X-Token": "hailhydra"},
        json={"id": "bazz", "title": "Bazz", "description": "Drop the bazz"},
    )
    assert response.status_code == 400
    assert response.json() == {"detail": "Invalid X-Token header"}


def test_create_existing_item():
    response = client.post(
        "/items/",
        headers={"X-Token": "coneofsilence"},
        json={
            "id": "foo",
            "title": "The Foo ID Stealers",
            "description": "There goes my stealer",
        },
    )
    assert response.status_code == 409
    assert response.json() == {"detail": "Item already exists"}
